package nj.yb.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import nj.yb.entity.group.GroupChat;
import nj.yb.entity.user.Friend;
import nj.yb.entity.user.User;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;

public class ChatClientHandler extends SimpleChannelInboundHandler {
    //登录同步信号量（初始计数为0,开始时由chatclient初始化）
    private final AtomicReference<CountDownLatch> loginLatchRef = new AtomicReference<>();
    //登录标记
    private volatile boolean isLoginSuccess = false;
    private volatile User loginUser = null;
    private volatile String loginFailReason;

    //注册同步信号量
    private final AtomicReference<CountDownLatch> registerLatchRef = new AtomicReference<>();
    //注册标记
    private volatile boolean isRegisterSuccess = false;
    private volatile String registerFailReason;

    //好友列表同步信号量
    private CountDownLatch friendListLatch;

    //历史消息同步信号量
    private CountDownLatch historyMessageLatch;

    //添加好友同步信号量
    private CountDownLatch addFriendLatch;

    //群聊列表同步信号量
    private CountDownLatch groupListLatch;

    public void setGroupListLatch(CountDownLatch groupListLatch) {
        this.groupListLatch = groupListLatch;
    }

    public void setAddFriendLatch(CountDownLatch addFriendLatch) {
        this.addFriendLatch = addFriendLatch;
    }

    public void setHistoryMessageLatch(CountDownLatch historyMessageLatch) {
        this.historyMessageLatch = historyMessageLatch;
    }

    public void setFriendListLatch(CountDownLatch friendListLatch) {
        this.friendListLatch = friendListLatch;
    }


    public void setRegisterLatch(CountDownLatch registerLatch){
        registerLatchRef.set(registerLatch);
    }

    public boolean isRegisterSuccess() {
        return isRegisterSuccess;
    }

    public String getRegisterFailReason() {
        return registerFailReason;
    }

    // 设置 loginLatch（线程安全）
    public void setLoginLatch(CountDownLatch loginLatch) {
        loginLatchRef.set(loginLatch);
    }


    public boolean isLoginSuccess() {
        return isLoginSuccess;
    }

    public User getLoginUser() {
        return loginUser;
    }

    public String getLoginFailReason() {
        return loginFailReason;
    }

    // 触发 countDown（从原子类中获取）
    private void countDownLoginLatch() {
        CountDownLatch latch = loginLatchRef.get();
        if (latch != null) {
            latch.countDown();
            loginLatchRef.set(null); // 重置
            //System.out.println("countDown 执行完成");
        }
    }

    private void countDownRegisterLatch(){
        CountDownLatch latch = registerLatchRef.get();
        if(latch != null){
            latch.countDown();
            registerLatchRef.set(null);

        }
    }

    //接收服务器消息时触发
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        String msg = o.toString();
        try{
            //解析JSON消息
            JSONObject json = JSON.parseObject(msg);
            String type = json.getString("type");
            switch (type){
                case "login_success":
                    JSONObject userJson = json.getJSONObject("user");
                    if(userJson != null){
                        this.loginUser = userJson.toJavaObject(User.class);
                        this.isLoginSuccess = true;
                    }else{
                        this.isLoginSuccess = false;
                        this.loginFailReason = "登录响应缺少用户信息";
                    }
                    countDownLoginLatch();
                    break;
                case "login_failed":
                    this.isLoginSuccess = false;
                    this.loginFailReason = json.getString("reason");
                    countDownLoginLatch();
                    break;
                case "register":
                    if(json.getString("msg") == null){
                        isRegisterSuccess = true;
                    }else{
                        registerFailReason = json.getString("msg");
                    }
                    countDownRegisterLatch();
                    break;
                case "friends":
                    System.out.println("====================好友列表=========================");
                    List<JSONObject> friends = json.getJSONArray("friends").toJavaList(JSONObject.class);
                    if(friends.size() == 0){
                        System.out.println("暂时还没有好友哦！快去添加吧！！！");
                    }else{
                        int cnt = 1;
                        for (JSONObject friend : friends) {
                            Friend friendJava = friend.toJavaObject(Friend.class);
                            String username = friendJava.getFriendInfo().getUsername();
                            System.out.println(cnt+"、"+username);
                            cnt++;
                        }
                    }
                    if(friendListLatch != null){
                        friendListLatch.countDown();
                        friendListLatch = null;
                    }
                    break;
                case "system":
                    // 系统消息
                    System.out.println("[系统] "+json.getString("time")+":" +json.getString("content"));
                    break;
                case "chat" :
                    //实时消息
                    System.out.println("[" +json.getString("prefix") + "]" +json.getString("time")+":" +json.getString("content"));
                    break;
                case "history" :
                    try{
                        if(json.getInteger("count") == 0){
                            System.out.println("你们之间还没有历史聊天信息，快去聊天吧！");
                        }else{
                            //历史消息
                            System.out.println("\n===========历史消息（共" + json.getInteger("count")+"条）==========");
                            List<JSONObject> messages = json.getJSONArray("messages").toJavaList(JSONObject.class);
                            //反转列表
                            for (int i = messages.size()-1; i >= 0; i--) {
                                JSONObject msgObj = messages.get(i);
                                String sender = msgObj.getString("sender");
                                String receiver = msgObj.getString("receiver");
                                String content = msgObj.getString("content");
                                String time = msgObj.getString("sendTime");

                                if("private".equals(msgObj.get("msgType"))){
                                    System.out.println("[私聊-"+sender+"与"+receiver+"]"+time + ": "+content);
                                }else{
                                    System.out.println("[群聊-" +sender+"] "+time+": "+content);
                                }
                            }
                            System.out.println("======历史消息结束======");
                            System.out.println("开始聊天吧！！！");
                        }
                    }catch (Exception e){
                        System.err.println("历史消息解析失败："+e.getMessage());
                    }finally {
                        if(historyMessageLatch != null){
                            historyMessageLatch.countDown();
                            historyMessageLatch = null;
                        }
                    }
                    break;

                case "add_friend":
                    String addMsg = json.getString("msg");

                    if(addMsg != null){
                        System.out.println(addMsg);
                    }else{
                        System.out.println("好友添加成功");
                    }

                    if(addFriendLatch != null){
                        addFriendLatch.countDown();
                        addFriendLatch = null;
                    }
                    break;
                case "notread" :
                    Integer size = json.getInteger("count");
                    String status = json.getString("status");
                    if(status.equals("success")){
                        if(size == 0){
                            System.out.println();
                        }else{
                            System.out.println("\n===========未读消息（共" + json.getInteger("count")+"条）==========");
                            List<JSONObject> notReadMessages = json.getJSONArray("notReadMessages").toJavaList(JSONObject.class);
                            //反转列表
                            for (int i = notReadMessages.size()-1; i >= 0; i--) {
                                JSONObject msgObj = notReadMessages.get(i);
                                String sender = msgObj.getString("sender");
                                String receiver = msgObj.getString("receiver");
                                String content = msgObj.getString("content");
                                String time = msgObj.getString("sendTime");

                                if("private".equals(msgObj.get("msgType"))){
                                    System.out.println("[私聊-"+sender+"与"+receiver+"]"+time + ": "+content);
                                }else{
                                    System.out.println("[群聊-" +sender+"] "+time+": "+content);
                                }
                            }
                            System.out.println("======未读消息结束======");
                        }
                    }else{
                        System.out.println(json.getString("msg"));
                        System.out.println("获取未读消息失败,但是您可以继续发送消息！");
                    }
                    break;
                case "grouplist":
                    Integer count = json.getInteger("count");
                    if(count == 0){
                        System.out.println("您还没有群聊，快去创建吧！！！");
                    }else{
                        JSONArray jsonArray = json.getJSONArray("groups");
                        List<GroupChat> groups = jsonArray.toJavaList(GroupChat.class);
                        System.out.println("==================群聊列表==================");
                        int cnt = 1;
                        for (GroupChat group : groups) {
                            Long id = group.getId();
                            String groupName = group.getGroupName();
                            System.out.println(cnt+"、 群聊id:"+id+"   群聊名称:"+groupName);
                            cnt++;
                        }
                    }
                    if(groupListLatch != null){
                        groupListLatch.countDown();
                        groupListLatch = null;
                    }
                    break;
                default:
                    System.out.println("收到消息：" +msg);
            }
        }catch (Exception e){
            System.out.println(msg);
            // 解析失败也需释放门闩，避免主线程永久等待
            countDownLoginLatch();

            countDownRegisterLatch();

            if (friendListLatch != null) {
                friendListLatch.countDown();
                friendListLatch = null;
            }

            if(historyMessageLatch != null){
                historyMessageLatch.countDown();
                historyMessageLatch = null;
            }
        }

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
